package requeteur.ejb.service;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import org.apache.commons.lang3.StringUtils;

import requeteur.ejb.commun.dto.InformationConnection;
import requeteur.ejb.commun.dto.ResultatRequete;
import requeteur.ejb.commun.dto.ResultatRequeteScript;
import requeteur.ejb.commun.dto.Table;
import requeteur.ejb.commun.exception.ConnectionException;
import requeteur.ejb.commun.outil.RequeteurUtils;
import requeteur.ejb.dao.DaoLancerRequete;

/**
 * @author Laurent
 * @version 0.1
 */
@Stateless
public class SrvLancerRequete {

	@EJB
	private DaoLancerRequete daoLancerRequete;

	/**
	 * Constructeur de la classe <code>SrvLancerRequete</code>.
	 */
	public SrvLancerRequete() {
	}

	public ResultatRequete lancerRequeteSelectAll(Table pTable, InformationConnection informationConnection) throws ConnectionException {
		return daoLancerRequete.lancerRequeteSelect("select * from " + pTable.getNom(), informationConnection);
	}

	public ResultatRequete lancerRequete(String pRequete, InformationConnection informationConnection) throws ConnectionException {
		ResultatRequete vResultatRequete = null;
		pRequete = StringUtils.remove(pRequete, ";");
		if (RequeteurUtils.isSelect(pRequete)) {
			vResultatRequete = daoLancerRequete.lancerRequeteSelect(pRequete, informationConnection);
		} else {
			vResultatRequete = daoLancerRequete.lancerRequeteUpdate(pRequete, informationConnection);
		}
		return vResultatRequete;
	}

	public ResultatRequeteScript lancerScript(String pScript, InformationConnection informationConnection) throws ConnectionException {
		StringTokenizer vStringTokenizer = new StringTokenizer(pScript, ";");
		List<String> vListeRequete = new ArrayList<String>();
		while (vStringTokenizer.hasMoreElements()) {
			String vRequete = vStringTokenizer.nextToken();
			if (!RequeteurUtils.isSelect(vRequete)) {
				vListeRequete.add(vRequete);
			}
		}
		return daoLancerRequete.lancerScript(vListeRequete, informationConnection);
	}

}
